/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.service.print.impl;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.CainiaoWaybillIiGetRequest;
import com.taobao.api.request.CainiaoWaybillIiGetRequest.*;

import com.taobao.api.response.CainiaoWaybillIiGetResponse;
import com.topisv.tms.entity.*;
import com.topisv.tms.mybatis.SqlMapDao;
import com.topisv.tms.repository.EdiOrderDao;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.WarehouseAddressService;
import com.topisv.tms.utils.InitProperties;
import com.topisv.tms.utils.PubUtil;
import com.topisv.tms.utils.WmsContants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 菜鸟打印
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 1.0.0
 */
@Component
public class CaiNiaoPrinteServiceNewImpl extends AbstractPrintService {
	
	private static final Logger logger = LoggerFactory.getLogger(CaiNiaoPrinteServiceNewImpl.class);

	
	/** 淘宝开放平台的地址--正式环境 */
	private static final String TOP_URL = InitProperties.get("top.api.url");

	private static final String APP_KEY = InitProperties.get("regAppKey");

	private static final String SECRET = InitProperties.get("regAppSecret");

	@Autowired
	private WarehouseAddressService warehouseAddressService;
	@Autowired
	private SqlMapDao sqlMapDao;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private EdiOrderDao ediOrderDao;

	@SuppressWarnings("unchecked")
    @Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public List<EdiOrder> doGetExpressNo(List<String> orderNoList, ExpressStyle template, String taskCode)
			throws Exception {

		// 第一步:基础数据
		ShopSource shopSource = shopSourceService.findByShopCode(WmsContants.SHOP_CODE_CN);
		
		// 获取仓库信息
		Map<String, WarehouseAddress> warehouseAddressMap = queryWarehouseAddress(taskCode);
		if (warehouseAddressMap == null) {
			throw new RuntimeException("找不到该商家与仓库的对应关系!");
		}
		
		List<EdiOrder> ediOrderList = sqlMapDao.selectList("ediOrderMapper.getEdiOrderListByOrdeno", orderNoList);

		// 第二步:循环订单取运单号
		TaobaoClient client = new DefaultTaobaoClient(TOP_URL, APP_KEY, SECRET);
		for (EdiOrder ediOrder : ediOrderList) {

			// 拼装xml
			CainiaoWaybillIiGetRequest req = getCaiNiaoStr(ediOrder, warehouseAddressMap, shopSource, template.getLogisticsCompany().getCompanyCode());
			logger.info("{}=菜鸟取单号报文={}", ediOrder.getOrdeno(), JSONObject.fromObject(req).toString());
			
			CainiaoWaybillIiGetResponse rsp = client.execute(req, shopSource.getTopisvSessionKey());
			logger.info("{}=菜鸟取单号返回的报文={}", ediOrder.getOrdeno(), JSONObject.fromObject(rsp).toString());
			
			// 解析返回结果
			if (!StringUtils.isBlank(rsp.getErrorCode())) {
				 throw new RuntimeException("取号失败:"+rsp.getMsg()+":"+rsp.getSubMsg());
				 
			} else {
				List<CainiaoWaybillIiGetResponse.WaybillCloudPrintResponse> results = rsp.getModules();
				if (results != null && !results.isEmpty()) {
					for (CainiaoWaybillIiGetResponse.WaybillCloudPrintResponse waybillCloudPrintResponse : results) {
						String waybillNo = waybillCloudPrintResponse.getWaybillCode();
						String printData= waybillCloudPrintResponse.getPrintData();
						ediOrder.setMailNo(waybillNo);
						ediOrder.setCacode(template.getLogisticsCompany().getCompanyCode());
						ediOrder.setCaname(template.getLogisticsCompany().getCompanyName());
						ediOrder.setPrintConfig(printData);
					}
				}
			}
		}

		ediOrderDao.save(ediOrderList);
		return ediOrderList;
	}

	public CainiaoWaybillIiGetRequest getCaiNiaoStr(EdiOrder ediOrder, Map<String, WarehouseAddress> warehouseAddressMap,
							  ShopSource shopSource, String companyCode) throws ApiException {

		WarehouseAddress warehouseAddress = warehouseAddressMap.get(ediOrder.getWarehouseCode());
		TaobaoClient client = new DefaultTaobaoClient(TOP_URL, APP_KEY, SECRET);
		CainiaoWaybillIiGetRequest req = new CainiaoWaybillIiGetRequest();
		CainiaoWaybillIiGetRequest.WaybillCloudPrintApplyNewRequest obj1 = new CainiaoWaybillIiGetRequest.WaybillCloudPrintApplyNewRequest();
		obj1.setCpCode(companyCode);//"POSTB"
		//obj1.setProductCode("目前已经不推荐使用此字段，请不要使用");
			UserInfoDto obj2 = new UserInfoDto();
				AddressDto obj3 = new AddressDto();
				obj3.setCity(warehouseAddress.getCityName());
				obj3.setDetail(warehouseAddress.getAddress());
				obj3.setDistrict(warehouseAddress.getDistName());
				obj3.setProvince(warehouseAddress.getProvName());
				//obj3.setTown(ediOrder.getTown());
			obj2.setAddress(obj3);
			obj2.setMobile(warehouseAddressMap.get(ediOrder.getWarehouseCode()).getMobile());
			obj2.setName(warehouseAddressMap.get(ediOrder.getWarehouseCode()).getContact());
			obj2.setPhone(warehouseAddressMap.get(ediOrder.getWarehouseCode()).getMobile());
		obj1.setSender(obj2);

		List<CainiaoWaybillIiGetRequest.TradeOrderInfoDto> list5 = new ArrayList<CainiaoWaybillIiGetRequest.TradeOrderInfoDto>();
		TradeOrderInfoDto obj6 = new TradeOrderInfoDto();
		//obj6.setLogisticsServices("如不需要特殊服务，该值为空");
		obj6.setObjectId(ediOrder.getCustomerOrdeno());//TODO
			OrderInfoDto obj8 = new OrderInfoDto();
			obj8.setOrderChannelsType(dealChannelsType(ediOrder.getSourcePlatformCode()));
			String[] orders2 = ediOrder.getOrdeno().split(";");
			obj8.setTradeOrderList(Arrays.asList(orders2));
		obj6.setOrderInfo(obj8);

			//TODO  循环item
			PackageInfoDto obj10 = new PackageInfoDto();
			obj10.setId(ediOrder.getOrdeno());//TODO
			List<Item> list12 = new ArrayList<Item>();
			Item obj13 = new Item();
			obj13.setCount(Long.valueOf(ediOrder.getSkuQty()));
			obj13.setName("0");
			list12.add(obj13);

			obj10.setItems(list12);
			//obj10.setVolume(1L);
			//obj10.setWeight(1L);
			obj10.setTotalPackagesCount(Long.valueOf(ediOrder.getSkuQty()));
			//obj10.setPackagingDescription("5纸3木2拖");
			//obj10.setGoodsDescription("服装");

		obj6.setPackageInfo(obj10);
			UserInfoDto obj15 = new UserInfoDto();
				AddressDto obj16 = new AddressDto();
				obj16.setCity(ediOrder.getCityna());
				obj16.setDetail(ediOrder.getAddres());
				obj16.setDistrict(ediOrder.getDistna());
				obj16.setProvince(ediOrder.getProvna());
				obj16.setTown( ediOrder.getTown());
			obj15.setAddress(obj16);
			obj15.setMobile(dealconsigneePhone(StringUtils.isEmpty(ediOrder.getMobile()) ? ediOrder.getTeleph() : ediOrder.getMobile()));
			obj15.setName(ediOrder.getRecena());
			obj15.setPhone(dealconsigneePhone(StringUtils.isEmpty(ediOrder.getMobile()) ? ediOrder.getTeleph() : ediOrder.getMobile()));
		obj6.setRecipient(obj15);


		obj6.setTemplateUrl("http://cloudprint.cainiao.com/template/standard/288948/39");
		obj6.setUserId(Long.valueOf(shopSource.getTopisvUserId()));
		list5.add(obj6);

		obj1.setTradeOrderInfoDtos(list5);
		//obj1.setStoreCode("553323");
		//obj1.setResourceCode("DISTRIBUTOR_978324");
		obj1.setDmsSorting(false);
		obj1.setThreePlTiming(false);
		obj1.setNeedEncrypt(true);
		req.setParamWaybillCloudPrintApplyNewRequest(obj1);
		return req;
	}

	public String getCaiNiaoPrintXml(EdiOrder ediOrder, Map<String, WarehouseAddress> warehouseAddressMap,
			ShopSource shopSource, String companyCode) {

		//发货地址 
		WarehouseAddress warehouseAddress = warehouseAddressMap.get(ediOrder.getWarehouseCode());
		
		JSONObject shippingAddress = new JSONObject();
		shippingAddress.put("province", warehouseAddress.getProvName());	// 省
		shippingAddress.put("city", warehouseAddress.getCityName());	// 市
		shippingAddress.put("area", warehouseAddress.getDistName());	// 区
		shippingAddress.put("address_detail", warehouseAddress.getAddress());// 详细地址

		// 收货地址
		JSONObject consigneeAddress = new JSONObject();
		consigneeAddress.put("address_detail", ediOrder.getAddres());// 详细地址
		consigneeAddress.put("town", ediOrder.getTown());//镇
		consigneeAddress.put("area", ediOrder.getDistna());// 区
		consigneeAddress.put("city", ediOrder.getCityna());// 市
		consigneeAddress.put("province", ediOrder.getProvna());	// 省
		
		JSONObject tradeOrderInfoCol = new JSONObject();
		tradeOrderInfoCol.put("consignee_address", consigneeAddress);
		tradeOrderInfoCol.put("consignee_name", ediOrder.getRecena());//收件人
		tradeOrderInfoCol.put("consignee_phone", dealconsigneePhone(StringUtils.isEmpty(ediOrder.getMobile()) ? ediOrder.getTeleph() : ediOrder.getMobile()));//收件人电话
		tradeOrderInfoCol.put("short_address", ediOrder.getToShortAddress());//大头笔
		tradeOrderInfoCol.put("product_type", "STANDARD_EXPRESS");//产品类型
		tradeOrderInfoCol.put("real_user_id", shopSource.getTopisvUserId());// 面单使用者的用户帐号id
		tradeOrderInfoCol.put("send_name", warehouseAddressMap.get(ediOrder.getWarehouseCode()).getContact());// 发货人名称
		tradeOrderInfoCol.put("send_phone", warehouseAddressMap.get(ediOrder.getWarehouseCode()).getMobile());// 发货人电话
		tradeOrderInfoCol.put("shipping_address", shippingAddress);
		tradeOrderInfoCol.put("waybill_code", ediOrder.getMailNo());//运单号
		
		JSONArray printCheckInfoCols = new JSONArray();
		printCheckInfoCols.add(tradeOrderInfoCol);

		JSONObject json = new JSONObject();
		json.put("cp_code", companyCode);
		json.put("print_check_info_cols", printCheckInfoCols);
		return json.toString();
	}

	/**
	 * 获取仓库信息
	 * 
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @param taskCode
	 *            任务号
	 * @return
	 */
	@SuppressWarnings("unchecked")
    private Map<String, WarehouseAddress> queryWarehouseAddress(String taskCode) {
		
		Map<String, WarehouseAddress> warehouseAddressMap = new HashMap<String, WarehouseAddress>();
		// 根据任务号查询商家仓库表的记录
		List<CustomerAreaGroup> list = PubUtil.convertListMapToObject(sqlMapDao.selectList("customerAreaGroupMapper.getCustomerAreaByTaskCode", taskCode), CustomerAreaGroup.class);
		if (list == null || list.isEmpty()) {
			return null;
		}
		
		CustomerAreaGroup customerAreaGroup = list.get(0);
		// 根据订单中仓库编码的查询仓库地址，并放到Map
		WarehouseAddress warehouseAddress = warehouseAddressService.findByWarehouseCode(customerAreaGroup.getAreaGroupCode());
		WarehouseAddress tempWarehouseAddress = new WarehouseAddress();
		BeanUtils.copyProperties(warehouseAddress, tempWarehouseAddress);
		
		// cainiaoAddressStatus等于1表示不用仓库信息，寄件人、寄件人电话使用管理发货人中的名称和电话;否则使用仓库信息
		if ("1".equals(customerAreaGroup.getCainiaoAddressStatus())) {
			List<Consignor> consignorList = PubUtil.convertListMapToObject(sqlMapDao.selectList("consignorMapper.getConsignorByCustomerCode", customerAreaGroup),Consignor.class);
			if (consignorList == null || consignorList.isEmpty()) {
				tempWarehouseAddress.setContact("");
				tempWarehouseAddress.setMobile("");
			} else {
				tempWarehouseAddress.setContact(consignorList.get(0).getName());
				tempWarehouseAddress.setMobile(consignorList.get(0).getMobile());
			}
		}
		
		warehouseAddressMap.put(warehouseAddress.getWarehouseCode(), tempWarehouseAddress);
		
		return warehouseAddressMap;
	}

	/**
	 * 订单来源字段的判断
	 * 
	 *
	 * @param orderChannelsType  订单来源
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	private static String dealChannelsType(String orderChannelsType) {
		if (StringUtils.isNotBlank(orderChannelsType)) {
			if (orderChannelsType.equals("OTHER") || "NULL".equals(orderChannelsType.toUpperCase())) {
				return "OTHERS";
			} else {
				return orderChannelsType;
			}
		} else {
			return "OTHERS";
		}
	}
	
	/**
	 * 
	 * 电话字段的判断
	 *
	 * @param phone 电话
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	public static String dealconsigneePhone(String phone) {
		if (!StringUtils.isBlank(phone) && phone.length() > 20) {
			return phone.substring(0, 20);
		}
		return phone;
	}

}
